package lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 这个方法在拿不到锁时会等待一定的时间，在时间期限之内如果还拿不到锁，就返回false。
 * 
 * @author lcx
 *
 */
public class ReentrantTryLockTimeTest {


	public static void main(String[] args) {
		ReentrantLock lock=new ReentrantLock();
		TryLockTimeThread td1=new TryLockTimeThread(lock);
		TryLockTimeThread td2=new TryLockTimeThread(lock);
		td1.start();
		td2.start();
	}

}

class TryLockTimeThread extends Thread
{
	ReentrantLock lock;
	public TryLockTimeThread(ReentrantLock lock)
	{
		this.lock=lock;
	}

	@Override
	public void run()
	{
		try {
			if(lock.tryLock(2000,TimeUnit.MILLISECONDS))
			{
				System.out.println("start......");
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				lock.unlock();
				System.out.println("end");
			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}